<template>
    <div class="h-full overflow-hidden flex flex-col">
        <div class="flex-1 overflow-auto pt-[26px] pb-[80px] px-[56px]">
            <div class="flex flex-row items-center">
                <a-flex align="center" :gap="14">
                    <a-flex justify="center" align="center" class="text-white text-xs font-medium size-5 rounded-full"
                        :class="step === 1 ? 'bg-theme' : 'bg-[#ACAEB2]'">
                        1
                    </a-flex>
                    <div class="text-lg font-bold" :class="step === 1 ? 'text-theme' : 'text-[#ACAEB2]'">工作时间</div>
                </a-flex>
                <img src="/images/worktime-arrow.png" :width="84" :height="10"
                    class="w-[84px] h-[10px] mx-[14px] object-cover block" />
                <a-flex align="center" :gap="14">
                    <a-flex justify="center" align="center" class="text-white text-xs font-medium size-5 rounded-full"
                        :class="step === 2 ? 'bg-theme' : 'bg-[#ACAEB2]'">
                        2
                    </a-flex>
                    <div class="text-lg font-bold" :class="step === 2 ? 'text-theme' : 'text-[#ACAEB2]'">
                        公司福利
                        <span class="text-sm !leading-7 align-top font-medium pl-[10px]">0/20</span>
                    </div>
                </a-flex>
            </div>
            <section class="bg-[#F5F7FA] rounded-sm box-border p-4 mt-3 2xl:w-[750px]" v-if="step === 1">
                <p class="text-sm text-primary">分享工作时间有什么用?</p>
                <p class="text-sm text-secondary mt-2">
                    工作时间是公司基本信息之一，调研显示85%的牛人看公司时会关注工作时间及休假安排，建议进行完善。
                </p>
                <p class="text-sm text-secondary">
                    * 标准时间仅为求职者提供参考，不代表公司下所有职位工作时间
                </p>
            </section>
            <section class="bg-[#F5F7FA] rounded-sm box-border p-4 mt-3 2xl:w-[750px]" v-else-if="step === 2">
                <p class="text-sm text-primary">填写公司福利有什么用?</p>
                <p class="text-sm text-secondary mt-2">
                    公司福利是公司基本信息之一，调研显示85%的牛人看公司时会关注公司福利信息;完善后，该类信息可作为公司亮点展示在不同推荐列表，吸引求职者关注。
                </p>
            </section>
            <section class="mt-6">
                <section v-if="step === 1">
                    <a-flex :gap="14" align="center" class="mb-6">
                        <div class="text-right text-sm text-primary" style="width: 78px;">
                            <span class="text-[#FC474C]">*</span>工作时间：
                        </div>
                        <a-flex :gap="8" align="center">
                            <TimePicker v-model:value="niumaState.startTime" format="HH:mm" value-format="HH:mm"
                                style="width: 160px; height: 36px;">
                                <template #suffixIcon>
                                    <GpFontIcon name="icon-rili" class="text-third" />
                                </template>
                            </TimePicker>
                            <span class="text-sm text-primary">~</span>
                            <TimePicker v-model:value="niumaState.endTime" format="HH:mm" value-format="HH:mm"
                                style="width: 160px; height: 36px;">
                                <template #suffixIcon>
                                    <GpFontIcon name="icon-rili" class="text-third" />
                                </template>
                            </TimePicker>
                        </a-flex>
                    </a-flex>
                    <a-flex :gap="14" align="center" class="mb-6">
                        <div class="text-right text-sm text-primary" style="width: 78px;">
                            加班情况：
                        </div>
                        <ul class="flex flex-row items-center gap-3">
                            <li v-for="item of pianjuOptons" :key="item.value" style="width: 100px; height: 36px;"
                                class="touchable-opacity flex flex-row justify-center items-center text-sm text-third hover:text-theme rounded-sm border border-solid border-[#CED4DB]"
                                :class="pianjuSelects.includes(item.value) ? '!text-theme bg-theme/4 border-theme' : ''"
                                @click="handlePianjuTap(item)">
                                {{ item.label }}
                            </li>
                        </ul>
                    </a-flex>
                    <a-flex :gap="14" align="center" class="mb-6">
                        <div class="text-right text-sm text-primary" style="width: 78px;">
                            休息时间：
                        </div>
                        <ul class="flex flex-row items-center gap-3">
                            <li v-for="item of boxueOptons" :key="item.value" style="width: 100px; height: 36px;"
                                class="touchable-opacity flex flex-row justify-center items-center text-sm text-third hover:text-theme rounded-sm border border-solid border-[#CED4DB]"
                                :class="boxueSelects.includes(item.value) ? '!text-theme bg-theme/4 border-theme' : ''"
                                @click="handleBoxueTap(item)">
                                {{ item.label }}
                            </li>
                        </ul>
                    </a-flex>
                    <a-button @click="handleSave()" :loading="submiting" type="primary" size="large"
                        style="width: 106px; margin-block-start: 48px;">下一步</a-button>
                </section>
                <section v-else-if="step === 2" class="outline-hidden">
                    <ul class="flex flex-row gap-8 border-b border-solid border-b-[#EEEEEE] sticky -top-[27px] bg-white z-10 overflow-auto">
                        <li v-for="item of fuliCases" :key="item.value"
                            :class="currentFuliCase === item.value ? 'border-b-[2px] border-solid border-b-theme !text-theme' : ''"
                            @click="handleChangeFuliItem(item)"
                            class="py-2 text-sm text-third cursor-pointer hover:text-theme flex-none">
                            {{ item.label }}
                        </li>
                    </ul>
                    <div class="mt-6">
                        <div class="mb-6" v-for="p of viewedFuliCases" :key="p.value">
                            <h5 class="text-base font-bold text-primary mb-3" :id="p.value">{{ p.label }}</h5>
                            <ul class="flex flex-col gap-2">
                                <li class="touchable-opacity item"
                                    :class="selectedFuliTitle.includes(item.title) ? 'active-item' : ''"
                                    v-for="item of p.list" :key="item.title" @click="handleFuliItemTap(item)">
                                    <GpFontIcon :name="item.icon" class="!text-[40px] !leading-10 text-[#ACAEB2]" />
                                    <div class="flex flex-col justify-center gap-[2px]">
                                        <h6 class="text-base text-primary">{{ item.title }}</h6>
                                        <div class="text-sm text-third text-justify maxline2">
                                            {{ item.desc }}
                                        </div>
                                    </div>
                                    <div class="flag">
                                        <GpFontIcon name="icon-gouxuan" class="icon" />
                                    </div>
                                </li>
                            </ul>
                        </div>
                        <div class="mb-6">
                            <h5 class="text-base font-bold text-primary mb-3" :id="FuliValue.custom">自定义</h5>
                            <ul class="flex flex-col gap-3">
                                <li class="flex flex-row gap-4" v-for="item of customFuliItems" :key="item.title">
                                    <div class="touchable-opacity item">
                                        <img :src="item.icon" :width="40" :height="40"
                                            class="block object-cover size-10" v-if="isImageIcon(item.icon)" />
                                        <GpFontIcon :name="item.icon" class="!text-[40px] !leading-10 text-[#ACAEB2]" v-else />
                                        <div class="flex flex-col justify-center gap-[2px]">
                                            <h6 class="text-base text-primary">{{ item.title }}</h6>
                                            <div class="text-sm text-third text-justify maxline2">
                                                {{ item.desc }}
                                            </div>
                                        </div>
                                    </div>
                                    <div class="flex flex-col gap-[14px] justify-center">
                                        <a-popconfirm title="确认删除？" @confirm="handleCustomAction(item, 'del')">
                                            <a-tooltip title="删除" placement="right">
                                                <GpFontIcon name="icon-shanchu3" class="!text-2xl !leading-none cursor-pointer hover:text-theme text-third"/>
                                            </a-tooltip>
                                        </a-popconfirm>
                                        <a-tooltip title="编辑" placement="right" @click="handleCustomAction(item, 'edit')">
                                            <GpFontIcon name="icon-bianji2" class="!text-2xl !leading-none cursor-pointer hover:text-theme text-third"/>
                                        </a-tooltip>
                                    </div>
                                </li>
                                <li @click="handleOpenAction()" class="touchable-opacity item !flex-col justify-center !gap-[2px] !border-dashed hover:!border-theme">
                                    <GpFontIcon name="icon-shangchuan"
                                        class="!text-[40px] !leading-none text-[#cdd4db]" />
                                    <span class="text-sm text-secondary">添加公司福利</span>
                                </li>
                            </ul>
                        </div>
                    </div>
                </section>
            </section>
        </div>
        <div
            class="px-[56px] box-border h-[88px] border-t border-solid border-t-[#EEEEEE] relative">
            <div class="flex flex-row justify-between items-center h-full 2xl:w-[750px] gap-3">
                <div class="flex-1 w-0 py-[10px] pl-[70px] outline-hidden">
                    <ul v-if="step === 2" class="flex flex-row items-center gap-1 flex-nowrap w-full overflow-auto">
                        <li v-for="item in allSelectedFuliTitle" :key="item" class="flex-none flex flex-row items-center gap-1 h-[28px] box-border px-3 rounded-[14px] text-theme bg-theme/6">
                            {{item}}
                            <GpFontIcon name="icon-guanbi" class="!text-base cursor-pointer" @click="handleDelItem(item)" />
                        </li>
                    </ul>
                </div>
                <a-button type="primary" class="rounded-sm w-[124px]" size="large" :loading="submiting"
                    @click="handleSave()">
                    保存
                </a-button>
            </div>
            <div v-if="step === 1"
                class="text-[#ACAEB2] text-sm flex flex-row items-center gap-1 cursor-pointer absolute left-[56px] top-[34px]">
                上传注意事项
                <GpFontIcon name="icon-yiwen1" />
            </div>
            <div v-else-if="step === 2"
                class="text-primary text-sm flex flex-row items-center absolute left-[56px] top-[34px]">
                已选
                <span class="text-theme px-1">{{ allSelectedFuliTitle.length }}</span>
                项
            </div>
        </div>
        <a-modal v-bind="defaultModalProps" v-model:open="showAction" :width="542" 
            :title="actionType === 'update' ? '编辑福利' : '添加福利'"
            :confirm-loading="uploadingLogo"
            @cancel="handleActionCancel()"
            @ok="handleActionConfirm()"
        >
            <div class="px-2 pt-8 pb-[56px] flex flex-col gap-8">
                <div class="flex flex-row items-center gap-3">
                    <div class="flex-none text-right text-sm text-secondary" style="width: 66px;">
                        <span class="text-[#FC474C]">* </span>福利标题
                    </div>
                    <a-input v-model:value="actionState.title" size="large" placeholder="请输入标题" />
                </div>
                <div class="flex flex-row items-center gap-3">
                    <div class="flex-none text-right text-sm text-secondary" style="width: 66px;">
                        福利备注
                    </div>
                    <a-input v-model:value="actionState.desc" size="large" placeholder="请输入备注（非必填）" />
                </div>
                <div class="flex flex-row items-center gap-3">
                    <div class="flex-none text-right text-sm text-secondary" style="width: 66px;">
                        <span class="text-[#FC474C]">* </span>福利图标
                    </div>
                    <div class="flex flex-row items-end gap-4">
                        <div @click="uploadLogo()" style="width: 80px; height: 80px;"
                            :class="uploadingLogo ? 'cursor-not-allowed' : 'cursor-pointer'"
                            class="relative rounded-sm overflow-hidden border border-dashed border-[#CED4DB] hover:border-theme bg-[#FCFBFF]">
                            <div class="size-full flex flex-col justify-center items-center">
                                <template v-if="uploadingLogo">
                                    <LoadingOutlined style="color: var(--color-theme); font-size: 20px;" />
                                    <span class="text-sm text-theme mt-1">上传中...</span>
                                </template>
                                <template v-else>
                                    <GpFontIcon name="icon-shangchuan"
                                        class="!text-[32px] !leading-none text-[#ced4db]" />
                                    <span class="text-sm text-[#ACAEB2]">上传图标</span>
                                </template>
                            </div>
                            <div class="absolute inset-0 bg-inherit group z-10" v-if="!uploadingLogo && actionState.icon">
                                <img :src="actionState.icon" width="100%" height="100%"
                                    class="size-full object-cover" v-if="isImageIcon(actionState.icon)" />
                                <div class="size-full flex justify-center items-center" v-else>
                                    <GpFontIcon :name="actionState.icon" class="!text-[40px] !leading-10 text-[#ACAEB2]" />
                                </div>
                                <div
                                    class="absolute inset-0 bg-black/60 hidden group-hover:flex flex-col justify-center items-center text-white">
                                    <GpFontIcon name="icon-zhongxinshangchuan" class="!text-[32px] !leading-none" />
                                    <span class="text-sm mt-[2px]">重新上传</span>
                                </div>
                            </div>
                        </div>
                        <p class="text-xs text-third">
                            若暂无图标，可以打开<span @click="handleOpenIcon()" class="touchable-opacity px-1 text-[#324366]">官方图标库</span>选取
                        </p>
                    </div>
                </div>
            </div>
        </a-modal>
        <a-modal v-bind="defaultModalProps"
            title="官方图标库"
            :width="660"
            v-model:open="showIcon"
            @cancel="handleIconCancel()"
            @ok="handleIconConfirm()"
        >
            <ul class="flex flex-row flex-wrap gap-3 px-2 pt-8 pb-[56px]">
                <li v-for="item of fuliPredefinedIcons" :key="item" @click="toggleIcon(item)"
                    :class="selectedIcon === item ? '!border-theme bg-[#F5F7FA]' : ''"
                    class="flex flex-row justify-center items-center border border-solid border-[#CED4DB] hover:border-theme/50 hover:bg-[#F5F7FA] touchable-opacity size-16 rounded-sm"
                >
                    <GpFontIcon :name="item" class="!text-[40px] !leading-10 text-[#ACAEB2]" />
                </li>
            </ul>
        </a-modal>
    </div>
</template>
<script lang="ts" setup>
import { postCompanyinfoWelfares, postCompanyinfoWorktime } from '@/api/siderBar/companyInfo'
import type { CompanyInfoResult, CompanyWelfareRequest, CompanyWorkTimeRequest } from '@/api/siderBar/model'
import { message, TimePicker } from 'ant-design-vue'
import { LoadingOutlined } from '@ant-design/icons-vue';
import { defaultModalProps } from '@/constants/comp-setting'
import { boxueOptons, FuliValue, pianjuOptons, type FuliCase, fuliCases, type FuliItem, fuliPredefinedIcons } from './data'
defineOptions({
    name: "CompanyFuLi"
})

type Props = CompanyInfoResult
const props = defineProps<Props>()
const emit = defineEmits<{
    refresh: []
}>()
const submiting = ref(false)
const step = ref(1)
const niumaState = ref(getInitialNiumaState())
const {
    selects: pianjuSelects,
    handleItemTap: handlePianjuTap
} = useOptionSelect({
    treatAll: false,
    availableOptions: pianjuOptons,
    rollbackSync: false,
    syncSelects(selects) {
        niumaState.value.overTime = selects[0]
    },
})
const {
    selects: boxueSelects,
    handleItemTap: handleBoxueTap
} = useOptionSelect({
    treatAll: false,
    availableOptions: boxueOptons,
    rollbackSync: false,
    syncSelects(selects) {
        niumaState.value.rest = selects[0]
    },
})
const currentFuliCase = ref<FuliValue>(FuliValue.tuijianfuli)
const viewedFuliCases = fuliCases.filter(l => l.value !== FuliValue.custom)
const selectedFuli = ref<Array<FuliItem>>([])
const selectedFuliTitle = computed(() => selectedFuli.value.map(l => l.title))
const customFuliItems = ref<FuliItem[]>([])
const actionState = ref<Partial<FuliItem>>({})
const actionType = ref<'create' | 'update'>('create')
const showAction = ref(false)
const showIcon = ref(false)
const selectedIcon = ref<string>()
const allSelectedFuliTitle = computed(() => selectedFuliTitle.value.concat(customFuliItems.value.map(l => l.title)))
watch([() => props.workTime, () => props.welfares], () => {
    populate()
}, {
    immediate: true
})
function toggleIcon(icon: string) {
    if (selectedIcon.value === icon) {
        selectedIcon.value = void 0
    } else {
        selectedIcon.value = icon
    }
}
const { uploadAction: uploadLogo, uploading: uploadingLogo } = useUpload({
    receiveResults([icon]) {
        if (icon) {
            actionState.value.icon = icon.fullName
        }
    },
    globalLoading: false
})
function handleCustomAction(item: FuliItem, action: "del" | 'edit') {
    if (action === 'del') {
        removeItem(customFuliItems.value, l => l.title === item.title)
    } else if (action === 'edit') {
        handleOpenAction(item)
    }
}
function handleOpenIcon() {
    showIcon.value = true
}
function handleIconCancel() {
    showIcon.value = false
    selectedIcon.value = void 0
}
function handleIconConfirm() {
    if (!selectedIcon.value) {
        message.warn('请选择图标')
        return
    }
    actionState.value.icon = selectedIcon.value
    handleIconCancel()
}
function handleOpenAction(item?: FuliItem) {
    if (item) {
        actionState.value = { ...item }
    }
    actionType.value = item ? 'update' : 'create'
    showAction.value = true
}
function handleActionCancel() {
    showAction.value = false
    actionType.value = 'create'
    actionState.value = {}
}
function handleActionConfirm() {
    const { desc, icon, title } = actionState.value
    const isEdit = actionType.value === 'update'
    if (!title || title.trim().length === 0) {
        message.warn('请输入标题')
        return
    }
    const _title = title.trim()
    if (!isEdit && allSelectedFuliTitle.value.includes(_title)) {
        message.warn('标题已存在')
        return
    }
    if (!icon) {
        message.warn('请设置图标')
        return
    }
    if (!isEdit) {
        customFuliItems.value.push({
            desc: desc || "",
            icon,
            parent: FuliValue.custom,
            title: _title
        })
    } else {
        const mutated = <FuliItem>actionState.value
        const index = customFuliItems.value.findIndex(l => l.title === mutated.title)
        customFuliItems.value[index] = {
            ...mutated
        }
    }
    handleActionCancel()
}
function handleChangeFuliItem(item: FuliCase) {
    if (currentFuliCase.value === item.value) return
    currentFuliCase.value = item.value
    const target = document.getElementById(item.value)
    if (target) {
        target.scrollIntoView({
            behavior: "instant",
            block: "start"
        })
    }
}
function handleFuliItemTap(item: FuliItem) {
    const index = selectedFuli.value.findIndex(l => l.title === item.title)
    if (~index) {
        selectedFuli.value.splice(index, 1)
    } else {
        selectedFuli.value.push(item)
    }
}
function populate() {
    if (props.workTime) {
        niumaState.value = { ...props.workTime }
        if (props.workTime.overTime) {
            pianjuSelects.value.length = 0
            pianjuSelects.value.push(props.workTime.overTime)
        }
        if (props.workTime.rest) {
            boxueSelects.value.length = 0
            boxueSelects.value.push(props.workTime.rest)
        }
    }
    if (props.welfares && props.welfares.length > 0) {
        selectedFuli.value.length = 0
        customFuliItems.value.length = 0
        props.welfares.forEach(item => {
            const target = findFuli(item)
            if (target) {
                selectedFuli.value.push({
                    desc: target.desc,
                    icon: target.icon,
                    title: target.title,
                    parent: target.parent,
                })
            } else {
                customFuliItems.value.push({
                    desc: item.desc,
                    icon: item.logo,
                    parent: FuliValue.custom,
                    title: item.title
                })
            }
        })
    }
    function findFuli(fuli: CompanyWelfareRequest) {
        for (let i = 0; i < viewedFuliCases.length; i++) {
            for (let j = 0; j < viewedFuliCases[i].list.length; j++) {
                if (viewedFuliCases[i].list[j].title === fuli.title) {
                    return viewedFuliCases[i].list[j]
                }
            }
        }
        return null
    }
}
function getInitialNiumaState(): CompanyWorkTimeRequest {
    return {
        startTime: "",
        endTime: "",
    }
}
async function handleSave() {
    try {
        submiting.value = true
        if (step.value === 1) {
            if (!niumaState.value.startTime || !niumaState.value.endTime) {
                message.error('请设置工作时间')
                return
            }
            await postCompanyinfoWorktime(niumaState.value)
            message.success('设置成功')
            step.value++;
        } else if (step.value === 2) {
            await handleSaveFuli()
            message.success('保存成功')
            emit('refresh')
        }
        submiting.value = false
    } catch (error) {
        console.log(error)
        submiting.value = false
    }
}
function handleSaveFuli() {
    const selects = [...selectedFuli.value, ...customFuliItems.value]
    return postCompanyinfoWelfares(selects.map(({desc, icon, title}) => ({ desc, logo: icon, title })))
}
function handleDelItem(title: string) {
    const i1 = selectedFuli.value.findIndex(l => l.title === title)
    if (~i1) {
        selectedFuli.value.splice(i1, 1)
        return
    }
    const i2 = customFuliItems.value.findIndex(l => l.title === title)
    if (~i2) {
        customFuliItems.value.splice(i2, 1)
        return
    }
}
function isImageIcon(icon: string) {
    return icon.startsWith("http")
}
</script>
<style lang="less" scoped>
@reference "../../../../../../../assets/styles/tailwind.css";

.item {
    width: 350px;
    height: 90px;
    border: 1px solid #CED4DB;
    padding-inline: 24px;
    @apply relative overflow-hidden rounded-sm flex flex-row items-center gap-6;

    &.active-item {
        border-color: var(--color-theme);
        background: #0768fa0a;

        .flag {
            display: block;
        }
    }

    .flag {
        display: none;
        width: 32px;
        height: 20px;
        border-inline-width: 16px;
        border-block-width: 10px;
        border-color: transparent;
        border-style: solid;
        border-block-start-color: var(--color-theme);
        border-inline-end-color: var(--color-theme);
        @apply absolute box-border top-0 right-0;

        .icon {
            color: white;
            position: absolute;
            top: -12px;
            right: -12px;
            font-size: 12px;
        }
    }
}
</style>